package com.gzu.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.constant.JwtClaimsConstant;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.context.BaseContext;
import com.gzu.shop.entity.Thing;
import com.gzu.shop.entity.ThingCollect;
import com.gzu.shop.entity.ThingWish;
import com.gzu.shop.exception.CollectionBusinessException;
import com.gzu.shop.exception.CollectionExistedException;
import com.gzu.shop.exception.DataEmptyException;
import com.gzu.shop.exception.WishExistedException;
import com.gzu.shop.mapper.ThingMapper;
import com.gzu.shop.mapper.ThingWishMapper;
import com.gzu.shop.service.ThingWishService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Clown
 */
@RestController
@RequestMapping("/thing-wish")
@AllArgsConstructor
@Slf4j
@Tag(name = "商品心愿单相关接口")
public class ThingWishController extends BaseController<ThingWishService, ThingWish> {
    private ThingWishMapper thingWishMapper;
    private ThingMapper thingMapper;
    @Operation(description = "查询用户的所有心愿")
    @GetMapping("/getAllWishes")
    public Result<List<Thing>> getAllWishes() {
        // 从threadLocal中取出用户数据
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
        // 根据取出的用户数据查询用户所有心愿
        QueryWrapper<ThingWish> thingWishQueryWrapper = new QueryWrapper<>();
        thingWishQueryWrapper.eq("user_id", userId);
        // 数据不存在直接返回
        if (!thingWishMapper.exists(thingWishQueryWrapper)) {
            return Result.success(ResultStatus.SUCCESS, null);
        }
        List<ThingWish> thingWishes = thingWishMapper.selectList(thingWishQueryWrapper);
        ArrayList<String> thingIds = new ArrayList<>();
        for (ThingWish thingWish : thingWishes) {
            thingIds.add(thingWish.getThingId());
        }

        return Result.success(ResultStatus.SUCCESS, thingMapper.selectBatchIds(thingIds));
    }


    @Override
    @PostMapping("/add")
    @Operation(description = "重写了父类方法，填充字段")
    @Transactional // 开启事务
    public Result<Void> addEntity(@RequestBody ThingWish entity) {
        // 获取用户ID
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
        log.info("############################");
        // 创建一个只含userID和thingId的实体，进行精确查询
        ThingWish thingWish = new ThingWish();
        thingWish.setThingId(entity.getThingId());
        thingWish.setUserId(String.valueOf(userId));
        log.info("thingWish:{}", thingWish);
        // 如果已经收藏过, 直接抛出异常
        if (thingWishMapper.exists(new QueryWrapper<>(thingWish))) {
            throw new WishExistedException(MessageConstant.WISH_EXISTS);
        }
        // 收藏日期
        entity.setCreateTime(String.valueOf(System.currentTimeMillis()));
        // 更新日期
        entity.setUpdateTime(String.valueOf(System.currentTimeMillis()));

        // 设置用户ID
        entity.setUserId(String.valueOf(userId));

        // 根据商品ID，将商品收藏数加1,推荐数加1
        Thing thing = thingMapper.selectById(entity.getThingId());
        thing.setWishCount(String.valueOf(Integer.parseInt(thing.getWishCount()) + 1));
        thing.setRecommendCount(String.valueOf(Integer.parseInt(thing.getRecommendCount()) + 1));

        thingMapper.updateById(thing);

        System.out.println("###################");
        System.out.println(entity);
        return super.addEntity(entity);
    }



    @Override
    @Operation(summary = "重写父类方法，实现通过id删除功能")
    @DeleteMapping("/del/{id}")
    @Transactional
    public Result<Void> deleteById(@PathVariable Long id) {
        // 商品id为空，排除空数据异常
        if (id == null) {
            throw new CollectionBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 查询商品是否存在
        Thing thing = thingMapper.selectById(id);
        // 商品不存在
        if (thing == null) {
            throw new CollectionBusinessException(MessageConstant.DATA_IS_NULL);
        }
        // 心愿数减1
        thing.setCollectCount(String.valueOf(Integer.parseInt(thing.getCollectCount()) - 1));
        // 更新商品时间
        thing.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        // 更新商品
        thingMapper.updateById(thing);
        // 查询收藏id
        // 获取用户ID

        // 获取userId
        // 获取用户ID
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
        // 通过userId和thingId查询数据
        QueryWrapper<ThingWish> thingWishQueryWrapper = new QueryWrapper<>();
        thingWishQueryWrapper.eq("user_id", userId);
        thingWishQueryWrapper.eq("thing_id", id);
        // 删除数据
        thingWishMapper.delete(thingWishQueryWrapper);

        return super.deleteById(id);
    }
}
